package com.gitee.zhangchenyan.takin.common.utils;

import lombok.SneakyThrows;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @Deacription IP帮助类
 * @Author zl
 * @Date 2022/5/16 14:08
 * @Version 1.0
 **/
public class HostUtils {

    public static void main(String[] args) {
        String hostIp = getHostIp();
        System.out.print(hostIp);
    }
    /**
     * @return 本机IP地址
     * @throws Exception 异常
     */
    @SneakyThrows
    public static String getHostIp(){
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = addresses.nextElement();
                if (ip instanceof Inet4Address
                        && !ip.isLoopbackAddress() //loopback地址即本机地址，IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                        && !ip.getHostAddress().contains(":")) {
                    return ip.getHostAddress();
                }
            }
        }
        throw new Exception("获取IP地址失败");
    }
}
